package com.shsubway.activity.manger;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.shsubway.R;
import com.shsubway.base.BaseActivity;
import com.shsubway.model.GroupEntity;
import com.shsubway.model.PostEntity;
import com.shsubway.model.StaffEntity;
import com.shsubway.utils.Constant;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 公司管理
 */
public class GroupManagerActivity extends BaseActivity {
    Intent intent;
    Bundle bundle;
    StaffEntity staffEntity;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.group_name)
    MaterialEditText groupName;
    @BindView(R.id.group_address)
    MaterialEditText groupAddress;
    @BindView(R.id.my_rec)
    ListView myRec;
    @BindView(R.id.fab_finish)
    FloatingActionButton fabFinish;
    AndroidNextInputs inputs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_manager);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> {
            setResult(1);
            finish();
        });
    }

    private void initView() {
        setTitleBar(toolbar, "公司信息");
        intent = getIntent();
        bundle = intent.getExtras();
        staffEntity = (StaffEntity) bundle.getSerializable(Constant.STAFFENTITY);
        inputs = new AndroidNextInputs();
        inputs.add(groupName, StaticScheme.NotBlank().msgOnFail("公司或部门名称不能为空"));
        inputs.add(groupAddress, StaticScheme.NotBlank().msgOnFail("公司或部门地址不能为空"));
        getGroupEntity();


//        addDate();
    }

    private void getGroupEntity() {
        BmobQuery<GroupEntity> groupEntityBmobQuery = new BmobQuery<>();
        groupEntityBmobQuery.addWhereEqualTo("objectId", staffEntity.getGroupId());
        groupEntityBmobQuery.findObjects(new FindListener<GroupEntity>() {
            @Override
            public void done(List<GroupEntity> list, BmobException e) {
                if (e == null) {
                    if (list.size() != 0) {
                        groupName.setText(list.get(0).getGroupName());
                        groupAddress.setText(list.get(0).getGroupAddress());
                    }
                } else {
                    toast("获取原始数据失败");
                }
            }
        });
    }

    @OnClick({R.id.fab_finish, R.id.fab_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fab_finish:
                if (inputs.test()) {
                    saveGroup();
                }

                break;
            case R.id.fab_add:
                editNicename();
                break;
        }
    }

    private void editNicename() {
        //创建对话框
        Dialog dialog = new Dialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit, null);
        //给Dialog中的子view设置事件监听
        view.findViewById(R.id.no).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView title = (TextView) view.findViewById(R.id.title);
        title.setText("职位名称");
        MaterialEditText edit_user_name = (MaterialEditText) view.findViewById(R.id.edit_user_name);
        edit_user_name.setHint("如：主管");
        view.findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edit_user_name.getText().toString().trim())) {
                    toast("名称不能为空");
                } else {
                    savePost(dialog, edit_user_name.getText().toString().trim());
                }
            }
        });
        dialog.setContentView(view);
        //自定义宽高（高度一般不用调整，在xml调整好就可以了，这里我只调整了宽度）
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = 900;
        dialog.getWindow().setAttributes(params);
        //show之前设置返回键无效，触摸屏无效
        dialog.setCancelable(false);
        //显示对话框
        dialog.show();
    }

    private void savePost(Dialog dialog, String postname) {
        PostEntity postEntity = new PostEntity();
        postEntity.setPost(postname);
        postEntity.setGroupId(staffEntity.getGroupId());
        postEntity.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                dialog.dismiss();
                if (e == null) {
                    toast("添加成功");
                    addDate();
                } else {
                    toast("添加失败");
                }
            }
        });


    }

    private void saveGroup() {
        Log.e("staffEntity===", staffEntity.toString());
        GroupEntity groupEntity = new GroupEntity();
        groupEntity.setGroupName(groupName.getText().toString().trim());
        groupEntity.setGroupAddress(groupAddress.getText().toString().trim());
        groupEntity.update(staffEntity.getGroupId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    toast("提交成功");
                    setResult(1);
                    finish();
                } else {
                    Log.e("AAA", e.toString());
                    toast("提交失败，请稍后重试。");
                }
            }
        });
    }


    private void addDate() {
        BmobQuery<PostEntity> postEntityBmobQuery = new BmobQuery<>();
        postEntityBmobQuery.addWhereEqualTo("groupId", staffEntity.getGroupId());
        postEntityBmobQuery.findObjects(new FindListener<PostEntity>() {
            @Override
            public void done(List<PostEntity> list, BmobException e) {

                if (e == null) {
                    if (list.size() != 0) {
                        initAdapter(list);
                    }
                } else {
                    Log.e("PPP", e.toString());
                }

            }
        });
    }

    private void initAdapter(List<PostEntity> list) {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getData(list));
        myRec.setAdapter(adapter);
    }

    private List<String> getData(List<PostEntity> list) {
        List<String> stringList = new ArrayList<>();
        for (PostEntity postEntity : list) {
            stringList.add(postEntity.getPost());
        }
        return stringList;
    }
}
